<template>
  <div>
    <v-card>
      <v-card-title>
        <v-text-field
          v-model="search"
          hide-details
          single-line
          :label="$t('searchInPage')"
          append-icon="search"
          v-if="$vuetify.breakpoint.smAndUp"
        ></v-text-field>
        <v-spacer v-if="$vuetify.breakpoint.smAndUp"></v-spacer>
        <span class="grey--text">{{ filterTagName }}</span>
        <v-spacer v-if="$vuetify.breakpoint.xsOnly"></v-spacer>
        <v-tooltip bottom v-if="enableManage">
          <v-btn icon slot="activator" :to="{ path: '/announcement/tags' }">
            <v-icon>book</v-icon>
          </v-btn>
          <span>{{$t('route.announcementTags')}}</span>
        </v-tooltip>
        <v-tooltip bottom v-if="enableManage">
          <v-btn icon slot="activator" :to="{ path: '/announcement/edit' }">
            <v-icon>alarm_add</v-icon>
          </v-btn>
          <span>{{$t('route.announcementEdit')}}</span>
        </v-tooltip>
        <v-tooltip bottom>
          <v-menu offset-y slot="activator">
            <v-btn icon slot="activator">
              <v-icon>filter_list</v-icon>
            </v-btn>
            <v-list>
              <v-list-tile v-for="tag in includeAllTags" :key="tag._id" @click="setFilterTagId(tag)">
                <v-list-tile-title>{{ tag.name }}</v-list-tile-title>
              </v-list-tile>
            </v-list>
          </v-menu>
          <span>{{$t('announcement.filter')}}</span>
        </v-tooltip>
      </v-card-title>
      <v-data-table
        :items="filterItems"
        :pagination.sync="pagination"
        :total-items="totalItems"
        :loading="loading"
        class="elevation-3"
        item-key="_id"
        hide-headers
      >
        <template slot="items" slot-scope="props">
          <tr>
            <td class="px-0">
              <v-list two-line>
                <v-list-tile avatar>
                  <v-list-tile-avatar @click="seeMore(props.item._id)" class="announcement-list__clickable">
                    <img :src="'data:image/png;base64,' + props.item.icon">
                  </v-list-tile-avatar>
                  <v-list-tile-content @click="seeMore(props.item._id)" class="announcement-list__clickable">
                    <v-list-tile-title>{{props.item.title}}</v-list-tile-title>
                    <v-list-tile-sub-title class="announcement-list__summary">{{props.item.summary}}</v-list-tile-sub-title>
                  </v-list-tile-content>
                  <v-list-tile-action>
                    <span class="grey--text">{{props.item.created_at | formatTime}}</span>
                    <v-btn icon v-if="enableManage" @click="handleDelete(props.item)"><v-icon color="secondary">delete</v-icon></v-btn>
                  </v-list-tile-action>
                </v-list-tile>
              </v-list>
            </td>
          </tr>
        </template>

      </v-data-table>
    </v-card>

    <v-dialog v-model="dialog" max-width="400px">
      <v-card>
        <v-card-title class="title">{{$t('irrecoverable')}}</v-card-title>
        <v-divider></v-divider>
        <v-card-text>
          你确定删除 <span class="subheading">{{delAnnTitle}}</span> ?
        </v-card-text>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn flat @click="dialog = false">{{$t('cancel')}}</v-btn>
          <v-btn color="error" @click="delAnnouncement">{{$t('sure')}}</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

  </div>
</template>

<script>
import { fetchAllAnn, fetchOnlyTags, removeAnn } from '@/api/announcement'

export default {
  data: () => ({
    dialog: false,
    search: '',
    totalItems: 0,
    filterTagId: 'allTags',
    filterTagName: '全部通知',
    delAnnTitle: '',
    delAnnId: '',
    items: [],
    tags: [],
    loading: true,
    pagination: {
      page: 1,
      rowsPerPage: 5
    }
  }),
  computed: {
    includeAllTags() {
      const copy = this.tags.slice()
      copy.push({ _id: 'allTags', name: '全部通知' })
      return copy
    },
    filterItems() {
      if (this.search) {
        return this.items.filter(v => v.title.indexOf(this.search) >= 0 || v.summary.indexOf(this.search) >= 0)
      }
      if (this.filterTagId === 'allTags') return this.items
      return this.items.filter(v => v.announcement_tag === this.filterTagId)
    },
    enableManage() {
      return this.$store.getters.roles.some(v => (v === 'admin' || v === 'announcement'))
    }
  },
  watch: {
    pagination: {
      handler() {
        this.getDataFromApi()
      },
      deep: true
    }
  },
  mounted() {
    this.getAnnTags()
    this.getDataFromApi()
  },
  methods: {
    seeMore(annId) {
      this.$router.push({ path: `/announcement/detail/${annId}` })
    },
    handleDelete(announcement) {
      this.delAnnTitle = announcement.title
      this.delAnnId = announcement._id
      this.dialog = true
    },
    delAnnouncement() {
      removeAnn(this.delAnnId).then(res => {
        if (res.status === 200) {
          for (const ann of this.items) {
            if (ann._id === this.delAnnId) {
              const index = this.items.indexOf(ann)
              this.items.splice(index, 1)
              this.dialog = false
            }
          }
          this.$notify.success('删除成功')
        } else {
          this.$notify.error('删除失败')
        }
      })
    },
    setFilterTagId(tag) {
      this.filterTagId = tag._id
      this.filterTagName = tag.name
    },
    getAnnTags() {
      fetchOnlyTags(this.$store.getters.team).then(res => {
        this.tags = res.data.tags
      })
    },
    getDataFromApi() {
      this.loading = true
      const { page, rowsPerPage } = this.pagination
      fetchAllAnn(this.$store.getters.team, page, rowsPerPage).then(res => {
        this.items = res.data.items
        this.totalItems = res.data.total
        this.loading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.announcement-list__summary {
  max-width: 750px;
  overflow: hidden;
  text-overflow:ellipsis;
  white-space: nowrap;
}
.announcement-list__clickable:hover {
  cursor: pointer;
}
</style>
